package boardgamer.yavalath.client;

import android.app.Activity;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import static boardgamer.yavalath.common.YavalathPlayerState.PlayerColor;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author garysoed
 */
public class Settings {

  private static Settings INSTANCE = null;

  public static void initialize(Activity activity) {
    INSTANCE = new Settings(activity);
  }

  public static Settings instance() {
    checkNotNull(INSTANCE, "Cannot call instance() before calling initialize()");
    return INSTANCE;
  }

  private static YavalathPlayer DEFAULT_LOCAL_PLAYERS[] = {
      new YavalathPlayer("Ysabel", PlayerColor.RED),
      new YavalathPlayer("Vorbis", PlayerColor.BLUE),
      new YavalathPlayer("Albert", PlayerColor.AQUA)
  };

  public static final String KEY_NAME_PLAYER_PREFIX = "name-player";
  public static final String KEY_COLOR_PLAYER_PREFIX = "color-player";

  public static final String KEY_MUTED = "muted";

  private final SharedPreferences preferences;

  private Settings(Activity activity) {
    this.preferences = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext());
  }

  public YavalathPlayer getPlayer(int playerId) {
    return loadPlayer(playerId);
  }

  public boolean isMuted() {
    return preferences.getBoolean(KEY_MUTED, false);
  }

  public void setMuted(boolean isMuted) {
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean(KEY_MUTED, isMuted);
    editor.commit();
  }
  
  public void setPlayerColor(int playerId, PlayerColor playerColor) {
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(createPlayerKey(KEY_COLOR_PLAYER_PREFIX, playerId), playerColor.name());
    editor.commit();
  }
  
  public void setPlayerName(int playerId, String playerName) {
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(createPlayerKey(KEY_NAME_PLAYER_PREFIX, playerId), playerName);
    editor.commit();
  }

  private YavalathPlayer loadPlayer(int playerId) {
    String name = preferences.getString(
        createPlayerKey(KEY_NAME_PLAYER_PREFIX, playerId),
        DEFAULT_LOCAL_PLAYERS[playerId].getName());
    PlayerColor color = PlayerColor.valueOf(
        preferences.getString(
            createPlayerKey(KEY_COLOR_PLAYER_PREFIX, playerId),
            DEFAULT_LOCAL_PLAYERS[playerId].getColor().toString())
    );
    return new YavalathPlayer(name, color);
  }

  private String createPlayerKey(String prefix, int playerId) {
    return prefix + "-" + playerId;
  }
}
